package com.bai.localshop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.bai.localshop.exception.BaseException;
import com.bai.localshop.mapper.ProductCategoryMapper;
import com.bai.localshop.mapper.ProductCategoryRelationMapper;
import com.bai.localshop.mapper.ProductMapper;
import com.bai.localshop.pojo.dto.ProductCategoryPageDTO;
import com.bai.localshop.pojo.dto.ProductCategorySaveDTO;
import com.bai.localshop.pojo.dto.ProductCategoryUpdateDTO;
import com.bai.localshop.pojo.dto.ProductUpdateStatusDTO;
import com.bai.localshop.pojo.entity.Product;
import com.bai.localshop.pojo.entity.ProductCategory;
import com.bai.localshop.pojo.entity.ProductCategoryRelation;
import com.bai.localshop.pojo.vo.ProductCategoryOptionVO;
import com.bai.localshop.pojo.vo.ProductCategoryPageVO;
import com.bai.localshop.pojo.vo.ProductCategoryVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bai.localshop.service.ProductCategoryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

/**
 * 商品分类服务实现类
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ProductCategoryServiceImpl extends ServiceImpl<ProductCategoryMapper, ProductCategory> implements ProductCategoryService {

    private final ProductCategoryMapper productCategoryMapper;
    private final ProductMapper productMapper;
    private final ProductCategoryRelationMapper productCategoryRelationMapper;

    /**
     * 获取商品分类列表（用于下拉选择）
     */
    @Override
    public List<ProductCategoryOptionVO> listCategoryOptions() {
        LambdaQueryWrapper<ProductCategory> queryWrapper = Wrappers.lambdaQuery(ProductCategory.class)
                .eq(ProductCategory::getStatus, 1)
                .orderByAsc(ProductCategory::getSort);
        List<ProductCategory> categoryList = baseMapper.selectList(queryWrapper);
        return BeanUtil.copyToList(categoryList, ProductCategoryOptionVO.class);
    }

    /**
     * 分页查询商品分类
     */
    @Override
    public IPage<ProductCategoryPageVO> pageQuery(ProductCategoryPageDTO requestParam) {
        // 设置默认分页查询参数
        int page = requestParam.getPage() != null ? requestParam.getPage() : 1;
        int pageSize = requestParam.getPageSize() != null ? requestParam.getPageSize() : 10;

        // 创建分页对象
        Page<ProductCategory> pageQuery = new Page<>(page, pageSize);

        // 构建查询条件
        LambdaQueryWrapper<ProductCategory> queryWrapper = Wrappers.lambdaQuery(ProductCategory.class);

        // 添加名称模糊查询条件
        if (requestParam.getName() != null && !requestParam.getName().trim().isEmpty()) {
            queryWrapper.like(ProductCategory::getName, requestParam.getName().trim());
        }

        // 添加状态查询条件
        if (requestParam.getStatus() != null) {
            queryWrapper.eq(ProductCategory::getStatus, requestParam.getStatus());
        }

        // 按排序字段升序
        queryWrapper.orderByAsc(ProductCategory::getSort);

        // 执行分页查询
        IPage<ProductCategory> categoryPage = productCategoryMapper.selectPage(pageQuery, queryWrapper);

        // 转换为VO对象并返回
        return categoryPage.convert(category -> BeanUtil.toBean(category, ProductCategoryPageVO.class));
    }

    /**
     * 查询所有启用的商品分类
     */
    @Override
    public List<ProductCategoryOptionVO> listEnabledCategories() {
        LambdaQueryWrapper<ProductCategory> queryWrapper = Wrappers.lambdaQuery(ProductCategory.class)
                .eq(ProductCategory::getStatus, 1)
                .orderByAsc(ProductCategory::getSort);
        List<ProductCategory> categoryList = baseMapper.selectList(queryWrapper);
        return BeanUtil.copyToList(categoryList, ProductCategoryOptionVO.class);
    }

    /**
     * 根据ID查询商品分类
     */
    @Override
    public ProductCategoryVO getCategoryById(Long id) {
        ProductCategory category = baseMapper.selectById(id);
        if (category == null) {
            throw new BaseException("商品分类不存在");
        }
        return BeanUtil.toBean(category, ProductCategoryVO.class);
    }

    /**
     * 修改商品分类
     */
    @Override
    public void updateCategory(ProductCategoryUpdateDTO requestParam) {
        // 检查分类名称是否已存在（排除当前分类）
        LambdaQueryWrapper<ProductCategory> queryWrapper = Wrappers.lambdaQuery(ProductCategory.class)
                .eq(ProductCategory::getName, requestParam.getName())
                .ne(ProductCategory::getId, requestParam.getId());

        if (baseMapper.selectCount(queryWrapper) > 0) {
            throw new BaseException("分类名称已存在，请重新输入");
        }

        // 更新分类信息
        LambdaUpdateWrapper<ProductCategory> updateWrapper = Wrappers.lambdaUpdate(ProductCategory.class)
                .set(ProductCategory::getName, requestParam.getName())
                .set(ProductCategory::getDescription, requestParam.getDescription())
                .set(ProductCategory::getIcon, requestParam.getIcon())
                .set(ProductCategory::getSort, requestParam.getSort())
                .set(ProductCategory::getStatus, requestParam.getStatus())
                .eq(ProductCategory::getId, requestParam.getId());

        baseMapper.update(updateWrapper);
    }

    /**
     * 删除商品分类
     */
    @Override
    public void deleteCategoryById(Long id) {
        ProductCategory category = productCategoryMapper.selectById(id);
        if (category == null) {
            throw new BaseException("商品分类不存在");
        }
        // 检查分类下是否有商品
        LambdaQueryWrapper<ProductCategoryRelation> queryWrapper = Wrappers.lambdaQuery(ProductCategoryRelation.class)
                .eq(ProductCategoryRelation::getCategoryId, id);
        if (productCategoryRelationMapper.selectCount(queryWrapper)>0){
            throw new BaseException("该分类下存在商品，不能删除");
        }

        productCategoryMapper.deleteById(id);
    }

    /**
     * 新增商品分类
     */
    @Override
    public void saveCategory(ProductCategorySaveDTO requestParam) {
        // 检查分类名称是否已存在
        LambdaQueryWrapper<ProductCategory> queryWrapper = Wrappers.lambdaQuery(ProductCategory.class)
                .eq(ProductCategory::getName, requestParam.getName());

        if (baseMapper.selectCount(queryWrapper) > 0) {
            throw new BaseException("分类名称已存在，请重新输入");
        }

        ProductCategory category = BeanUtil.toBean(requestParam, ProductCategory.class);
        baseMapper.insert(category);
    }

    /**
     * 修改商品分类状态
     * @param requestParam
     */
    @Override
    public void updateStatus(ProductUpdateStatusDTO requestParam) {
        Integer status = requestParam.getStatus();
        Long id = requestParam.getId();
        // 校验状态值
        if (status != 0 && status != 1) {
            throw new BaseException("状态值不合法");
        }
        ProductCategory productCategory = baseMapper.selectById(id);
        if (productCategory == null) {
            throw new BaseException("商品分类不存在");
        }
        //分类下有商品不能禁用
        LambdaQueryWrapper<ProductCategoryRelation> queryWrapper = Wrappers.lambdaQuery(ProductCategoryRelation.class)
                .eq(ProductCategoryRelation::getCategoryId, id);
        if (productCategoryRelationMapper.selectCount(queryWrapper)>0){
            throw new BaseException("商品分类下有商品，不能禁用");
        }
        LambdaUpdateWrapper<ProductCategory> updateWrapper = Wrappers.lambdaUpdate(ProductCategory.class)
                .set(ProductCategory::getStatus, status)
                .eq(ProductCategory::getId, id);
        baseMapper.update(updateWrapper);
    }
}